
# 2020/7/15
# encoding=utf-8
from dnac_f import *
"""
功能：
    1.获取所管辖的所有网元，并打印展示
    2.然后可以让用户选择某一个网元
    3.然后获取该指定网元的所有接口信息，并打印展示
"""


# -----获取控制器所管辖的所有网元的粗略信息并罗列打印-----
def get_device_list(controller):

    device_dict = controller.get('network-device')

    # 接下来筛选感兴趣的信息，便于tabulate打印
    device_list = []
    for i, item in enumerate(device_dict['response']):
        uptime = "N/A" if item['upTime'] is None else item['upTime']
        device_list.append([i+1, item["hostname"], item["managementIpAddress"], item['platformId'],
                            item["type"], item['softwareVersion'], item['role'], uptime])
    #  利用tabulate以图表的形式打印出来
    print(tabulate(device_list, headers=['序号', 'hostname', 'ip', 'platformId', 'type', 'softwareVersion', 'role', 'uptime'], tablefmt="rst"))
    get_device_id(device_dict, controller)


# -----遍历取出每一个网元的ID，准备获取其接口信息-----
def get_device_id(device_json, controller):
    for device in device_json['response']:
        print("Fetching Interfaces for Device Id ----> {}".format(device['id']))
        print('\n')
        get_device_int(device['id'], controller)
        print('\n')


# -----获取网元的接口信息并罗列打印-----
def get_device_int(device_id, controller):
    querystring = {"macAddress": device_id}
    interface_info_json = controller.get('interface', params=querystring)

    # 接下来筛选感兴趣的信息，便于tabulate打印
    interface_list = []
    for i, item in enumerate(interface_info_json['response']):
        interface_list.append([i + 1, item["portName"], item["vlanId"], item['portMode'], item["portType"],
                               item['duplex'], item['status'], item['lastUpdated']])
    #  利用tabulate以图表的形式打印出来
    print(tabulate(interface_list,
                   headers=['序号', 'portName', 'vlanId', 'portMode', 'portType', 'duplex', 'status', 'lastUpdated'],
                   tablefmt="rst"))


if __name__ == "__main__":
    my_dnac = dnac()
    get_device_list(my_dnac)